package web.controller;

import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import service.configuration.IConfiguration;
import service.mailing.IMailer;

/**
 * <b>bugReportController </b>
 * <p>bugReportController controle les requêtes pour signaler un bug.</p>
 * 
 */

@Controller
public class BugReportController {
	
	
	/**
     * Repr&eacute;sente le service d'envoi d'eMail
     */
	@Resource
	private IMailer mailer;
	
	/**
     * Repr&eacute;sente le service de configuration
     */
	@Resource
	private IConfiguration config;
	
	
	/**
     * Controlleur qui renvoi la page de rapport de bug
     */
	@RequestMapping(value = "/bugReport.htm", method = RequestMethod.GET)
	public String handleRequestRegister(@RequestHeader("Referer") String referer,
			HttpSession session, ModelMap model)  {
		
		if(referer!=null){
			return "bugReport";
		}else{
			return "redirect : treeview.htm";
		}
			
	}
	
	/**
     * Controlleur qui recoi la description du bug et la renvoyer a l'administrateur
     */
	
	@RequestMapping(value = "/bugReport.htm", method = RequestMethod.POST)
	public String onSubmitbugReport(@RequestHeader("Referer") String referer,HttpSession session,
								@RequestParam(value = "idLDAP", required = false) String idLDAP,
								@RequestParam(value = "subject", required = false) String subject,
								@RequestParam(value = "mail", required = false) String mail,
								ModelMap model) throws Exception {
		
		if(idLDAP.compareTo("")==0)
			idLDAP="inconnu";
		if(subject.compareTo("")==0)
			subject="vide";
		if(mail.compareTo("")==0)
			mail="vide";
		
		mailer.sendHtmlMail(config.getApplicationAdminMail(), "Rapport bug [ASOF]", 
				"<p>Message envoyé par : "+idLDAP+" .</p>"+
				"<p>Le : "+new Date()+" .</p>" +
				"<p>Sujet : "+subject+" .</p>"+
				"<p>Contenu :</P>"+
				mail);
		
		JSONObject json = new JSONObject();
		
		json.put("success", true);
		json.put("message", "Rapport bien envoyé");
			
		model.addAttribute("jsonArray", json);
		return "json";
	}
}